package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetize.plus.entity.dto.BarrageDTO;
import com.poetize.plus.entity.po.Barrage;
import com.poetize.plus.entity.po.User;
import com.poetize.plus.entity.vo.BarrageVO;
import com.poetize.plus.mapper.BarrageMapper;
import com.poetize.plus.mapper.UserMapper;
import com.poetize.plus.service.BarrageService;
import com.poetize.plus.utils.BaseEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zuosy
 * @created 2024/5/14 14:13
 */
@Service
@RequiredArgsConstructor
public class BarrageServiceImpl extends ServiceImpl<BarrageMapper, Barrage> implements BarrageService {

    private final UserMapper userMapper;

    @Override
    public Long sendBarrage(BarrageDTO barrageDTO) {
        Barrage barrage = BarrageDTO.convertDTO(barrageDTO);
        int insert = baseMapper.insert(barrage);
        if (insert > 0){
            return barrage.getId();
        }
        return 0L;
    }

    @Override
    public List<BarrageVO> getBarrageList() {
        List<Barrage> barrages = lambdaQuery()
                .orderByDesc(BaseEntity::getCreateTime)
                .last("limit 200")
                .list();

        List<String> username = barrages.stream().map(BaseEntity::getCreateBy).toList();
        if (CollectionUtils.isEmpty(username)){
            return new ArrayList<>();
        }

        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getUsername, username));

        List<BarrageVO> result = new ArrayList<>();
        barrages.forEach(barrage -> {
            Optional<User> userOptional = users.stream().filter(f -> f.getUsername().equals(barrage.getCreateBy())).findFirst();
            if (userOptional.isPresent()){
                User user = userOptional.get();
                BarrageVO vo = BarrageVO.convert(barrage, user.getAvatar());
                result.add(vo);
            }
        });
        return result;
    }
}
